# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper

  def base_language_only
    yield if Locale.base?
  end

  def not_base_language
    yield unless Locale.base?
  end

  def flash_div *keys
    keys.collect { |key| content_tag(:div, flash[key],
                                     :class => "flash #{key}") if flash[key] }.join
  end
    
  # Return a link for use in layout navigation. 
  def nav_link(text, controller, action="index", opts = {})
    args = {:controller => controller, :action => action}.merge(opts)
    link_to_unless_current text, args
  end 

  # return a table with some specified number of columns
  def generate_table(items = [], opts = {})
    args = {:class => 'generated_table', :cols => '3'}.merge(opts)
    table = "<table class=\"#{args[:class]}\">"
    table += '<tr>'
    count = 0
    items.each do |item|
      if count.to_s == args[:cols]
        table += "</tr>\n<tr>"
      end
      table += "<td>#{item}</td>"
      count += 1
    end
    table += "</tr>"
    table += "</table>"
  end

  # excerpt a string
  def excerpt(string, length = 20)
    if string.nil? or string.blank?
      return ""
    end
    words = string.split(/\s+/)
    if words.length <= length
      return string
    end
    return words.first(length).join(' ') + '...'
  end


  # Get the current locale name
  def get_current_locale_name
    if session[:locale]
      loc = Locale.new(session[:locale])
      if loc && loc.language && loc.language.native_name
        return loc.language.native_name
      end
    end
    return nil
  end

  # Get the locale choice link
  def get_all_locales
    @locale_codes = LOCALES.keys
    @locales = []
    LOCALES.each do |key, loc|
      unless loc == session[:locale] || key == session[:locale]
        loc_obj = Locale.new(loc)
        if (loc_obj && loc_obj.language && loc_obj.language.native_name)
          @locales.push [
                loc_obj.language.native_name, 
                key, 
                url_for(:locale => loc, :action => params[:action], :controller => params[:controller], :id => params[:id] ) ]
        end
      end
    end
    @locales = @locales.sort_by {|name, key, url| name }
    if session[:locale] && !session[:locale].nil?
      loc_obj = Locale.new(session[:locale])
      if loc_obj && loc_obj.language  && loc_obj.language.native_name
        @locales.unshift [ 
                loc_obj.language.native_name, 
                session[:locale], 
                url_for(:locale => session[:locale], :action => params[:action], :controller => params[:controller], :id => params[:id] ) ]
      end
    end
    return @locales
  end

  # Helper to inform the user that a translation is not
  # yet available. 
  def translation_availability_for object_name, facet, message = nil
    not_base_language do
      message ||= content_tag 'p', '(Translation not available)'.t
      object = instance_variable_get "@#{object_name}" 
      message if object && !object.send( facet ).blank? && object.send( "#{facet}_is_base?" )
    end
  end

  def user_permissions(user)
    perms = []
    perms.push '<abbr title="Volcom">V</abbr>' if user.is_volcom
    perms.push '<abbr title="OTW">O</abbr>' if user.is_otw
    perms.push '<abbr title="Translator">T</abbr>' if user.is_translator
    if perms.length > 0
      return "<small>[" + perms.join(',') + "]</small>"
    end
  end

  # Find all members of a particular class who match a given query
  def find_queried(query, classname, opts = {})
    query_hits = []
    if query && !query.blank?
      query = query.split(/\s+/).join(' OR ') if opts[:match_any]
      query_hits = classname.find_by_contents(query, :limit => :all)
    end    
  end

  # Find all members of a particular class who have a given skill
  def find_skilled(skills_to_match, classname, opts = {})
    skill_hits = []
    if skills_to_match.length > 0
      firstskill = true
      skills_to_match.each do |skill| 
        if opts[:match_any]
          skill_hits = firstskill ? classname.find_all_by_skill(skill) : skill_hits | classname.find_all_by_skill(skill)
        else
          skill_hits = firstskill ? classname.find_all_by_skill(skill) : skill_hits & classname.find_all_by_skill(skill)
        end
        firstskill = false
      end
    end
    return skill_hits
  end

  # Find the union of a search by query and skills
  def find_union(opts = {})
    if opts[:query] && !opts[:query].blank? && opts[:skills].length > 0
      if opts[:match_any]
        return opts[:query_hits] | opts[:skill_hits]
      else  
        return opts[:query_hits] & opts[:skill_hits]
      end
    elsif opts[:query] && !opts[:query].blank? 
      return opts[:query_hits]
    elsif opts[:skills].length > 0
      return opts[:skill_hits]
    end
    return nil
  end

  # Used to determine if a given skill has been checked in the form
  def skill_checked?(skill)
    !params["skill_#{skill.id}"].nil?
  end
  
  # Return true if a parameter corresponding to the given symbol was posted
  # eg: a form posted with a :user parameter
  def param_posted?(symbol)
    request.post? and params[symbol]
  end

  # Helper to check if a user is logged in
  def logged_in?
    not session[:user_id].nil? # is session user id nil? if not, then we are logged in
  end

  # Helper to get a user if a user is logged in
  def get_user
    begin
      if logged_in?
        @user = User.find(session[:user_id])
      end
    rescue
      User.logout!(session, cookies)
    end
  end

end
